﻿using Microsoft.WindowsAzure.Storage.Blob;
using PetkaWebDav.Server.Framework.BaseClasses;
using PetkaWebDav.Server.Framework.Enums;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PetkaWebDav.Handler.AzureBlob.Handlers
{
    /// <summary>
    /// Custom implementation example for DavGet.
    /// </summary>
    public sealed class DavGet : DavGetBase
    {
        public DavGet()
        {
            this.ProcessDavRequest += new DavProcessEventHandler(DavGet_ProcessDavRequest);
        }

        private void DavGet_ProcessDavRequest(object sender, EventArgs e)
        {
            CloudBlockBlob _fileInfo = null;

            try
            {
                _fileInfo = RequestWrapper.DownloadBlobAttributes(base.RelativeRequestPath);
            }
            catch (Exception ex)
            {
                base.AbortRequest(ServerResponseCode.NotFound);
            }

            if (_fileInfo == null)
                base.AbortRequest(ServerResponseCode.NotFound);
            else
            {
                using (MemoryStream _fileStream = RequestWrapper.DownloadBlob(_fileInfo.Name))
                {
                    _fileStream.Position = 0;
                    long _fileSize = _fileStream.Length;
                    byte[] _responseBytes = new byte[_fileSize];

                    _fileStream.Read(_responseBytes, 0, (int)_fileSize);

                    base.ResponseOutput = _responseBytes;

                    _fileStream.Close();
                }
            }
        }
    }
}
